package com.iplay.实战java高并发程序设计.chapter2;

/**
 * @author dangwu
 * @since 2021/4/29 4:18 下午
 */
public class GoodSuspend {
    public static final Object u = new Object();

    public static class ChangeObjectThread extends Thread{
        volatile boolean suspendMe = false;
        public void suspendMe(){
            this.suspendMe = true;
        }

        public void resumeMe(){
            this.suspendMe = false;
            synchronized (this){
                notify();
            }
        }

        @Override
        public void run() {
            while (true){
                synchronized (this){
                    while (suspendMe){
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                synchronized (u){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("in ChangeObjectThread");
                }
                Thread.yield();
            }
        }
    }

    public static class ReadObjectThread extends Thread{
        @Override
        public void run() {
            while (true){
                synchronized (u){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("in ReadObjectThread");
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ChangeObjectThread t1 = new ChangeObjectThread();
        ReadObjectThread t2 = new ReadObjectThread();
        t1.start();
        t2.start();
        Thread.sleep(5000);
        t1.suspendMe();
        System.out.println("t1 suspend 3 sec");
        Thread.sleep(10000);
        System.out.println("t1 resume");
        t1.resumeMe();
    }

}
